#include "uart_core.h"
#include <QThread>
#include <QTextStream>
#include <cstdio>
#include <QDir>

QString UART_PATH_FILE = "./UartDebugFile";

namespace UartNamespace {
Uartcore::Uartcore(QObject *parent) : QObject(parent), ring_buffer_(UART_RING_BUFFER_SIZE){
  serial_port_ = new QSerialPort;
  (void)parent;

  Worker *worker = new Worker;
  worker->SetUartCoreObj(this);
  worker->moveToThread(&workerThread);
  //operate信号发射后启动线程工作
  connect(this, SIGNAL(operate(const int)), worker, SLOT(doWork(int)));
  //该线程结束时销毁
  connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
  //线程结束后发送信号，对结果进行处理
  connect(worker, SIGNAL(resultReady(int)), this, SLOT(handleResults(int)));
  //启动线程
  workerThread.start();
  //发射信号，开始执行
  qDebug()<<"emit the signal to workerThread execute!---------------------------------";
  qDebug()<<"     current thread ID:"<<QThread::currentThreadId()<<'\n';
  emit operate(0);
}

Uartcore::~Uartcore() {
  workerThread.quit();
  workerThread.wait();
  qDebug()<<"~Uartcore" << endl;
}

void Uartcore::UnInit() {
  delete serial_port_;
  serial_port_ = nullptr;
  qDebug()<<"UnInit" << endl;
}

QStringList Uartcore::UartPortScan() {
  QStringList serial_list;
  foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
    qDebug() << info.description() + '(' + info.portName() + ')';
    serial_list.append(info.description() + '(' + info.portName() + ')');
  }
  return serial_list;
}

bool Uartcore::open(QString serial_name, int baud_rate, int data_bit, int parity_bit, int stop_bit, int flow_control) {
  serial_port_->setPortName(serial_name);
  if (serial_port_->open(QIODevice::ReadWrite)) {
    serial_port_->setBaudRate(baud_rate);
    serial_port_->setDataBits((QSerialPort::DataBits)data_bit );
    serial_port_->setParity((QSerialPort::Parity)parity_bit );
    serial_port_->setStopBits((QSerialPort::StopBits)stop_bit );
    serial_port_->setFlowControl((QSerialPort::FlowControl)flow_control );
    //serial_port_->setReadBufferSize(0);//設置緩衝區大小為無窮大
    connect(serial_port_, SIGNAL(readyRead()), this, SLOT(ReadUpperCpuUartData()));
    connect(serial_port_, SIGNAL(readyRead()), this, SIGNAL(UartDataReadReadySignal()));

    SaveFileInit(serial_name, UART_PATH_FILE);

    return true;
  }

  return false;
}

void Uartcore::SaveFileInit(QString serial_name, QString &folder_path) {
  QDateTime currentDateTime = QDateTime::currentDateTime();
  QString file_name = serial_name + "_" + currentDateTime.toString("yyyy-MM-dd-hh-mm-ss") + "_File.txt";
  // 确保文件夹路径以斜杠开头和结尾
  if (!folder_path.endsWith("/")) {
    folder_path += "/";
  }

  // 构建完整的文件路径
  QString filePath = folder_path + file_name;

  // 确保文件夹存在，如果不存在则创建
  QDir dir(folder_path);
  if (!dir.exists()) {
    if (!dir.mkpath(".")) { // 使用"."来创建当前路径
      qDebug() << "无法创建文件夹：" << folder_path;
      return;
    }
  }
  save_file_.setFileName("./" + filePath);
}

void Uartcore::close() {
  serial_port_->clear();
  serial_port_->close();
}

void Uartcore::write(QByteArray &data){
  serial_port_->write(data);
}

void Uartcore::SaveUartReadDataToFile(const QByteArray data, size_t data_length) {
  if (save_file_.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) {
    QTextStream out(&save_file_);
    for (size_t i = 0; i < data_length; i++) {
      out << data[i];
    }
    save_file_.close();
  } else {
    qDebug() << "无法打开文件";
  }
}

// 读取下位机发来数据
void Uartcore::ReadUpperCpuUartData() {
  const QByteArray data = serial_port_->readAll();
  size_t data_length = data.size();
  qDebug()<<"+++++++++++++++++++++++++++++++++" << endl;
  qDebug()<<"ReadUpperCpuUartData:" << data;
  SaveUartReadDataToFile(data, data_length);
  UartBufferWrite(data);
  emit operate(UART_DATA_READ_READY);
}

void Uartcore::UartBufferWrite(QByteArray data) {
  ring_buffer_.write(data, data.size());
}

void Uartcore::UartBufferReady() {
  emit UartDataReadReadySignal();
}

QByteArray Uartcore::UartBufferRead() {
  QByteArray read;
  char ringbuffer[UART_RING_BUFFER_SIZE];
  int read_length = sizeof(ringbuffer);
  if (ring_buffer_.read( (char*)ringbuffer, read_length)) {
    read.append(ringbuffer, read_length);
  }

  qDebug() << "UartBufferRead:" << read;
  return read;
}

void Uartcore::UartReadBufferClean(){

}

QByteArray Uartcore::HexStringToByteArray(QString HexString)
{
  bool ok;
  QByteArray data;
  HexString = HexString.trimmed();
  HexString = HexString.simplified();
  QStringList sl = HexString.split(" ");

  foreach (QString s, sl){
    if(!s.isEmpty()){
      char c = static_cast<char>(s.toInt(&ok, 16) & 0xFF);
      if(ok){
        data.append(c);
      } else {
        QMessageBox::warning(nullptr, tr("Error: "),
        QString(tr("Illegal hex string:"))+ QString(" \"%1\"").arg(s));
      }
    }
  }
  return data;
}
}
